<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title th:text="${plan.title} + ' - 智能旅游路线推荐系统'">旅游计划详情</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <style>
        .map-container {
            height: 500px;
            margin-bottom: 20px;
            border-radius: 8px;
            overflow: hidden;
        }
        .attraction-card {
            margin-bottom: 15px;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        .attraction-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
        }
        .day-section {
            background: #f8f9fa;
            padding: 20px;
            margin-bottom: 20px;
            border-radius: 8px;
            border-left: 4px solid #007bff;
        }
        .attraction-info {
            display: flex;
            align-items: center;
            margin-bottom: 10px;
        }
        .attraction-number {
            background: #007bff;
            color: white;
            width: 30px;
            height: 30px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 15px;
            font-weight: bold;
        }
        .favorite-btn {
            position: fixed;
            top: 100px;
            right: 20px;
            z-index: 1000;
        }
    </style>
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container">
            <a class="navbar-brand" href="/travel/">智能旅游路线推荐</a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav">
                    <li class="nav-item">
                        <a class="nav-link" href="/travel/">首页</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/travel/generate">生成行程</a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <div class="container my-5">
        <div class="row">
            <div class="col-lg-8">
                <h2 th:text="${plan.title}">旅游计划详情</h2>
                <p class="text-muted">
                    <i class="bi bi-geo-alt"></i>
                    <span th:text="${plan.city}">城市</span> · 
                    <i class="bi bi-calendar"></i>
                    <span th:text="${plan.days}">天数</span>天 · 
                    <i class="bi bi-clock"></i>
                    <span th:text="${#dates.format(plan.createTime, 'yyyy-MM-dd HH:mm')}">创建时间</span>
                </p>
                
                <!-- 地图容器 -->
                <div id="map" class="map-container"></div>
                
                <!-- 每日行程 -->
                <div th:each="dayNum : ${#numbers.sequence(1, plan.days)}">
                    <div class="day-section">
                        <h4 class="mb-3">
                            <i class="bi bi-calendar-day"></i>
                            第<span th:text="${dayNum}">1</span>天
                        </h4>
                        <div th:each="detail : ${plan.details}" th:if="${detail.dayNum == dayNum}">
                            <div class="attraction-info" 
                                 th:attr="data-longitude=${detail.attraction.longitude}, 
                                          data-latitude=${detail.attraction.latitude}, 
                                          data-name=${detail.attraction.name}"
                                 onclick="showOnMap(this)">
                                <div class="attraction-number" th:text="${detail.visitOrder}">1</div>
                                <div>
                                    <h6 th:text="${detail.attraction.name}">景点名称</h6>
                                    <p class="text-muted mb-1" th:text="${detail.attraction.description}">景点描述</p>
                                    <small class="text-muted">
                                        <i class="bi bi-geo-alt"></i>
                                        <span th:text="${detail.attraction.address}">地址</span>
                                    </small>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="mb-2">
                    <label for="routeType" class="form-label me-2">出行方式：</label>
                    <select id="routeType" class="form-select w-auto d-inline">
                        <option value="driving">驾车</option>
                        <option value="walking">步行</option>
                        <option value="transit">公交</option>
                    </select>
                </div>
                <div id="routeSteps" class="mt-3"></div>
            </div>
            
            <div class="col-lg-4">
                <!-- 收藏按钮 -->
                <button id="favoriteBtn" class="btn btn-outline-primary favorite-btn" 
                        th:attr="data-plan-id=${plan.id}"
                        onclick="toggleFavorite(this)">
                    <i class="bi bi-heart"></i>
                    收藏计划
                </button>
                
                <!-- 行程概览 -->
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0">行程概览</h5>
                    </div>
                    <div class="card-body">
                        <p><strong>目的地：</strong><span th:text="${plan.city}">城市</span></p>
                        <p><strong>天数：</strong><span th:text="${plan.days}">天数</span>天</p>
                        <p><strong>景点数量：</strong><span th:text="${#lists.size(plan.details)}">数量</span>个</p>
                        <hr>
                        <div id="routeDayBtns" class="mb-2">
                            <!-- 动态生成天数按钮 -->
                        </div>
                        <button class="btn btn-primary w-100" onclick="showRoute(currentDay)">
                            <i class="bi bi-map"></i>
                            显示第<span id="currentDayLabel">1</span>天路线
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <footer class="bg-light py-3 mt-5">
        <div class="container text-center">
            <p>&copy; 2023 智能旅游路线推荐系统</p>
        </div>
    </footer>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <script th:inline="javascript">
        // 获取计划数据
        const planData = /*[[${plan}]]*/ {};
        const amapKey = 'cbbb13cd8839a33a693a9d10c4fbe070';
        
        // 初始化地图
        let map;
        let markers = []; // 用于景点标记
        
        // 用于路线相关的全局变量
        window.routePolyline = null;
        window.routeMarkers = [];

        let currentDay = 1; // 默认选中第一天
        
        function initMap() {
            // 加载高德地图API
            const script = document.createElement('script');
            script.src = `https://webapi.amap.com/maps?v=2.0&key=${amapKey}`;
            script.onload = function() {
                // 确保加载所有需要的插件：Driving (驾车), Walking (步行), Transfer (公交)
                AMap.plugin(['AMap.Driving', 'AMap.Walking', 'AMap.Transfer'], function() {
                    // 计算地图中心点
                    const attractions = planData.details || [];
                    if (attractions.length > 0) {
                        const firstAttraction = attractions[0].attraction;
                        const center = [firstAttraction.longitude, firstAttraction.latitude];

                        // 创建地图实例
                        map = new AMap.Map('map', {
                            zoom: 12,
                            center: center
                        });

                        // 添加景点标记
                        addMarkers();
                    } else {
                        // 如果没有景点，也初始化地图，但中心点可设为城市中心或默认
                        map = new AMap.Map('map', {
                            zoom: 10,
                            center: [116.40, 39.90] // 默认北京中心
                        });
                    }
                });
            };
            document.head.appendChild(script);
        }
        
        function addMarkers() {
            const attractions = planData.details || [];
            attractions.forEach((detail, index) => {
                const attraction = detail.attraction;
                const marker = new AMap.Marker({
                    position: [attraction.longitude, attraction.latitude],
                    title: attraction.name,
                    label: {
                        content: `${detail.dayNum}-${detail.visitOrder}`,
                        direction: 'top'
                    }
                });
                
                marker.setMap(map);
                markers.push(marker);
                
                // 添加信息窗体
                const infoWindow = new AMap.InfoWindow({
                    content: `
                        <div style="padding: 10px;">
                            <h6>${attraction.name}</h6>
                            <p style="margin: 5px 0; color: #666;">${attraction.description}</p>
                            <p style="margin: 5px 0; font-size: 12px; color: #999;">
                                <i class="bi bi-geo-alt"></i> ${attraction.address}
                            </p>
                        </div>
                    `,
                    offset: new AMap.Pixel(0, -30)
                });
                
                marker.on('click', function() {
                    infoWindow.open(map, marker.getPosition());
                });
            });
        }
        
        function renderRouteDayBtns() {
            const days = planData.days || 1;
            let html = '';
            for (let i = 1; i <= days; i++) {
                html += `<button type="button" class="btn btn-outline-secondary btn-sm me-1 mb-1" onclick="selectRouteDay(${i})">第${i}天</button>`;
            }
            $('#routeDayBtns').html(html);
        }

        function selectRouteDay(day) {
            currentDay = day;
            $('#currentDayLabel').text(day);
            showRoute(day);
        }

        function showRoute(dayNum) {
            if (!map) {
                $('#routeSteps').html('<div class="text-danger">地图未加载完成，请稍后重试。</div>');
                return;
            }

            // 1. 每次规划前，先清除旧的路线和标记
            if (window.routePolyline) {
                map.remove(window.routePolyline);
                window.routePolyline = null;
            }
            if (window.routeMarkers.length > 0) {
                map.remove(window.routeMarkers);
                window.routeMarkers = [];
            }
            $('#routeSteps').html(''); // 清空路线详情区域

            const routeType = $('#routeType').val();
            const attractions = (planData.details || []).filter(d => d.dayNum === dayNum);
            
            if (attractions.length < 2) {
                $('#routeSteps').html('<div class="text-info">当天景点不足2个，无法规划路线。</div>');
                return;
            }

            const sortedAttractions = attractions.sort((a, b) => a.visitOrder - b.visitOrder);
            const path = sortedAttractions.map(detail => [
                parseFloat(detail.attraction.longitude),
                parseFloat(detail.attraction.latitude)
            ]);

            // 检查是否有无效坐标，如果有则无法规划
            if (path.some(p => isNaN(p[0]) || isNaN(p[1]))) {
                $('#routeSteps').html('<div class="text-danger">景点经纬度无效，请检查数据。</div>');
                return;
            }

            const origin = path[0].join(',');
            const destination = path[path.length - 1].join(',');
            const waypointsArr = path.slice(1, path.length - 1);
            const waypoints = waypointsArr.map(p => p.join(',')).join('|');

            let apiUrl = '/api/route/' + routeType;
            let requestData = { origin: origin, destination: destination };

            if (routeType === 'driving' && waypoints) {
                requestData.waypoints = waypoints;
            }
            if (routeType === 'transit') {
                requestData.city = planData.city;
            }

            // 显示加载动画
            $('#routeSteps').html('<div class="text-secondary">正在规划路线...</div>');

            $.ajax({
                url: apiUrl,
                method: 'GET',
                data: requestData,
                success: function(response) {
                    let res = response;
                    if (typeof res === 'string') {
                        try {
                            res = JSON.parse(res);
                        } catch (e) {
                            console.error('JSON解析失败:', e);
                            $('#routeSteps').html('<div class="text-danger">路线数据解析异常。</div>');
                            return; // 提前退出
                        }
                    }

                    // 如果API返回状态不为1，则显示错误信息
                    if (res.status !== '1') {
                        const errMsg = res.info || '路线规划失败';
                        $('#routeSteps').html(`<div class="text-danger">${errMsg} (错误码: ${res.infocode || '未知'})</div>`);
                        console.error('高德API返回错误:', res);
                        return; // 提前退出
                    }

                    let polylineStr = '';
                    let steps = [];

                    if (routeType === 'driving' && res.route && res.route.paths && res.route.paths.length > 0) {
                        // v3版本API：polyline分散在每个step中，需要合并
                        steps = res.route.paths[0].steps || [];
                        const polylineParts = steps.map(step => step.polyline).filter(Boolean);
                        polylineStr = polylineParts.join(';');
                    } else if (routeType === 'walking' && res.route && res.route.paths && res.route.paths.length > 0) {
                        // v3版本API：polyline分散在每个step中，需要合并
                        steps = res.route.paths[0].steps || [];
                        const polylineParts = steps.map(step => step.polyline).filter(Boolean);
                        polylineStr = polylineParts.join(';');
                    } else if (routeType === 'transit' && res.route && res.route.transits && res.route.transits.length > 0) {
                        let segments = res.route.transits[0].segments || [];
                        steps = segments.map(seg => ({
                            instruction: seg.instruction || (seg.walking && seg.walking.instruction) || (seg.bus && seg.bus.buslines && seg.bus.buslines[0] && seg.bus.buslines[0].instruction) || '乘坐公交',
                            step_distance: seg.walking ? seg.walking.distance : (seg.bus && seg.bus.buslines && seg.bus.buslines[0] && seg.bus.buslines[0].distance) || ''
                        }));
                        polylineStr = segments.map(seg => {
                            if (seg.walking && seg.walking.polyline) return seg.walking.polyline;
                            // 公交线路的polyline通常在buslines里
                            if (seg.bus && seg.bus.buslines && seg.bus.buslines[0] && seg.bus.buslines[0].polyline) return seg.bus.buslines[0].polyline;
                            return '';
                        }).filter(Boolean).join(';');
                    }

                    // --- 调试输出 --- (非常重要，请将这些日志截图给我)
                    console.log('--- 路线规划调试信息 ---');
                    console.log('出行方式:', routeType);
                    console.log('后端返回的完整数据 (res):', res); // 展开这个对象，查看res.route.paths[0].polyline
                    
                    // 详细展开路径信息
                    if (res.route && res.route.paths && res.route.paths.length > 0) {
                        console.log('=== 详细路径信息 ===');
                        console.log('res.route.paths[0]:', res.route.paths[0]);
                        
                        // 检查每个step的polyline
                        const steps = res.route.paths[0].steps || [];
                        console.log('steps数量:', steps.length);
                        const stepsWithPolyline = steps.filter(step => step.polyline);
                        console.log('包含polyline的steps数量:', stepsWithPolyline.length);
                        console.log('前3个包含polyline的steps:', stepsWithPolyline.slice(0, 3));
                        
                        console.log('==================');
                    }
                    
                    console.log('从响应中提取的 polylineStr (原始字符串):', polylineStr);
                    console.log('从响应中提取的 steps:', steps);
                    console.log('--------------------------');
                    // --- 调试输出结束 ---

                    if (polylineStr) {
                        console.log('=== polyline 解析过程 ===');
                        console.log('原始 polylineStr:', polylineStr);
                        console.log('polylineStr 前20个字符:', polylineStr.substring(0, 20));
                        console.log('polylineStr 后20个字符:', polylineStr.substring(polylineStr.length - 20));
                        
                        const polylineArr = polylineStr.split(';').map(item => {
                            const coords = item.split(',').map(Number);
                            // 确保坐标是有效的数字
                            if (coords.length === 2 && !isNaN(coords[0]) && !isNaN(coords[1])) {
                                return coords;
                            }
                            return null; // 标记为无效坐标
                        }).filter(Boolean); // 过滤掉所有标记为null的无效坐标

                        // --- 调试输出 --- (请将此日志截图给我)
                        console.log('解析后的 polylineArr (数组):', polylineArr);
                        console.log('polylineArr 长度:', polylineArr.length);
                        console.log('前5个坐标点:', polylineArr.slice(0, 5));
                        console.log('后5个坐标点:', polylineArr.slice(-5));
                        console.log('======================');
                        // --- 调试输出结束 ---

                        if (polylineArr.length > 0) {
                            window.routePolyline = new AMap.Polyline({
                                path: polylineArr,
                                strokeColor: routeType === 'driving' ? '#007bff' : (routeType === 'walking' ? '#28a745' : '#ff9800'),
                                strokeWeight: 6,
                                strokeOpacity: 0.9,
                                isOutline: true,
                                outlineColor: '#fff',
                                lineJoin: 'round'
                            });
                            window.routePolyline.setMap(map);

                            // 起点、终点标记
                            let startMarker = new AMap.Marker({
                                position: polylineArr[0],
                                map: map,
                                icon: 'https://webapi.amap.com/theme/v1.3/markers/n/start.png',
                                anchor: 'bottom-center'
                            });
                            let endMarker = new AMap.Marker({
                                position: polylineArr[polylineArr.length - 1],
                                map: map,
                                icon: 'https://webapi.amap.com/theme/v1.3/markers/n/end.png',
                                anchor: 'bottom-center'
                            });
                            window.routeMarkers.push(startMarker, endMarker);
                            
                            map.setFitView(window.routePolyline); // 适配路线视野
                        } else {
                            $('#routeSteps').html('<div class="text-danger">获取到轨迹但解析后无效，请检查数据。</div>');
                        }
                    } else {
                        $('#routeSteps').html('<div class="text-danger">未能获取到有效的路线轨迹。</div>');
                    }

                    // 显示导航详情
                    if (steps && steps.length > 0) {
                        let html = '<div class="mt-3"><h5 class="mb-2">导航步骤</h5><ol class="list-group list-group-numbered">';
                        steps.forEach((step, idx) => {
                            html += `<li class="list-group-item">${step.instruction || ''} <span class="text-muted">${step.step_distance ? '(' + step.step_distance + '米)' : ''}</span></li>`;
                        });
                        html += '</ol></div>';
                        $('#routeSteps').append(html); // 使用append，保持加载中提示
                    } else if (res.status === '1') { // 成功但无steps
                        $('#routeSteps').append('<div class="text-info">未获取到详细导航步骤。</div>');
                    }

                },
                error: function(xhr, status, error) {
                    console.error('后端服务请求失败:', xhr, status, error);
                    $('#routeSteps').html('<div class="text-danger">后端服务请求异常，请稍后重试。</div>');
                }
            });
        }
        
        function showOnMap(element) {
            if (!map) return;
            
            const lng = parseFloat(element.getAttribute('data-longitude'));
            const lat = parseFloat(element.getAttribute('data-latitude'));
            const name = element.getAttribute('data-name');
            
            map.setCenter([lng, lat]);
            map.setZoom(15);
            
            // 显示信息窗体
            const infoWindow = new AMap.InfoWindow({
                content: `<div style="padding: 10px;"><h6>${name}</h6></div>`,
                offset: new AMap.Pixel(0, -30)
            });
            
            infoWindow.open(map, [lng, lat]);
        }
        
        function toggleFavorite(element) {
            const planId = element.getAttribute('data-plan-id');
            const btn = $('#favoriteBtn');
            const isFavorited = btn.hasClass('btn-primary');
            
            $.ajax({
                url: isFavorited ? '/travel/cancelFavorite' : '/travel/favorite',
                method: 'POST',
                data: { planId: planId },
                success: function(response) {
                    if (response.success) {
                        if (isFavorited) {
                            btn.removeClass('btn-primary').addClass('btn-outline-primary');
                            btn.html('<i class="bi bi-heart"></i> 收藏计划');
                        } else {
                            btn.removeClass('btn-outline-primary').addClass('btn-primary');
                            btn.html('<i class="bi bi-heart-fill"></i> 已收藏');
                        }
                    }
                },
                error: function() {
                    alert('操作失败，请重试');
                }
            });
        }
        
        // 出行方式切换时自动刷新路线
        $(document).on('change', '#routeType', function() {
            showRoute(currentDay);
        });
        
        // 页面加载完成后初始化地图和天数按钮
        $(document).ready(function() {
            initMap();
            renderRouteDayBtns();
            // 默认显示第一天的路线
            showRoute(currentDay);
        });
    </script>
</body>
</html>
